<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加分类按钮 -->
      <el-row>
        <el-col
          ><el-button type="primary" @click="addGoodsCateBtn"
            >添加分类</el-button
          ></el-col
        >
      </el-row>
      <!-- 商品分类列表 -->
      <tree-table
        :data="goodsCateData"
        :columns="columns"
        show-index
        index-text="#"
        :selection-type="false"
        border
        show-row-hover
        :expand-type="false"
        max-height="600"
      >
        <!-- 状态作用域插槽 -->
        <template v-slot:catDeleted="scope">
          <!-- {{ scope.row }} -->
          <el-icon
            v-if="scope.row.cat_deleted"
            class="el-icon-error"
            style="color:#F56C6C"
          ></el-icon>
          <el-icon
            v-else
            class="el-icon-success"
            style="color:#409EFF"
          ></el-icon>
        </template>
        <!-- 排序作用域插槽 -->
        <template v-slot:catLevel="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level === 1" type="success"
            >二级</el-tag
          >
          <el-tag v-else type="warning">三级</el-tag>
        </template>
        <!-- 操作作用域插槽 -->
        <template v-slot:handle="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="modGoodsCateBtn(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="delGoodsCateBtn(scope.row)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="getGoodsCateListParams.pagenum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="getGoodsCateListParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="goodsCateDataTotal"
      >
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加分类"
        :visible.sync="addGoodsCatedialog"
        width="50%"
        @close="cloAddGoodsCate"
      >
        <el-form
          ref="addGoodsCateFormRef"
          :model="addGoodsCateFormParams"
          label-width="80px"
          :rules="addGoodsCateFormRules"
          hide-required-asterisk
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addGoodsCateFormParams.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
            <el-cascader
              v-model="selectValCate"
              :props="props"
              :options="goodsCateDataBeforeTwo"
              @change="changeNode"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addGoodsCatedialog = false">取 消</el-button>
          <el-button type="primary" @click="subAddGoodsCate">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户对话框 -->
      <el-dialog
        title="修改分类"
        :visible.sync="modGoodsCatedialog"
        width="50%"
      >
        <el-form
          ref="modGoodsCateFormRef"
          :model="modGoodsCateFormParams"
          label-width="80px"
          :rules="modGoodsCateFormRules"
          hide-required-asterisk
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="modGoodsCateFormParams.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="modGoodsCatedialog = false">取 消</el-button>
          <el-button type="primary" @click="subModGoodsCate">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //  获取商品分类参数
      getGoodsCateListParams: {
        type: [],
        pagenum: 1,
        pagesize: 10
      },
      // 商品列表数据
      goodsCateData: [],
      // 商品列表数据总数
      goodsCateDataTotal: 0,
      // 树状表格参数
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          prop: 'cat_deleted',
          type: 'template',
          template: 'catDeleted'
        },
        {
          label: '排序',
          prop: 'cat_level',
          type: 'template',
          template: 'catLevel'
        },
        {
          label: '操作',
          type: 'template',
          template: 'handle'
        }
      ],
      // 是否显示添加分类对话框
      addGoodsCatedialog: false,
      // 添加分类参数
      addGoodsCateFormParams: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      // 添加分类验证规则
      addGoodsCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 前二级商品列表数据
      goodsCateDataBeforeTwo: [],
      // 级联选择配置
      props: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true
      },
      // 级联选择项
      selectValCate: [],
      // 是否显示修改分类对话框
      modGoodsCatedialog: false,
      // 修改分类参数
      modGoodsCateFormParams: {
        cat_name: '',
        cat_id: 0
      },
      // 修改分类验证规则
      modGoodsCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getGoodsCateList()
  },
  methods: {
    //   获取商品分类列表
    async getGoodsCateList() {
      const { data } = await this.$http.get('categories', {
        params: this.getGoodsCateListParams
      })
      if (data.meta.status !== 200) {
        return this.$message.error('获取商品分类列表失败')
      }
      // this.$message.success('获取商品分类列表成功')
      console.log('获取商品分类列表成功')
      this.goodsCateData = data.data.result
      this.goodsCateDataTotal = data.data.total
    },
    // 分页操作函数
    handleSizeChange(size) {
      this.getGoodsCateListParams.pagesize = size
      this.getGoodsCateList()
    },
    handleCurrentChange(page) {
      this.getGoodsCateListParams.pagenum = page
      this.getGoodsCateList()
    },
    //  是否显示添加分类按钮
    addGoodsCateBtn() {
      this.getGoodsCateBeforeTwo()
      this.addGoodsCatedialog = true
    },
    //  获取前二级分类列表
    async getGoodsCateBeforeTwo() {
      const { data } = await this.$http.get('categories', {
        params: { type: [2] }
      })
      if (data.meta.status !== 200) {
        return this.$message.error('获取前二级商品分类列表失败')
      }
      // this.$message.success('获取前二级商品分类列表成功')
      console.log('获取前二级商品分类列表成功')
      this.goodsCateDataBeforeTwo = data.data
    },
    // 当级联选择器发生改变
    changeNode() {
      // 判断级联选择器选中值，给接口参数赋值
      if (this.selectValCate.length === 0) {
        this.addGoodsCateFormParams.cat_pid = 0
        this.addGoodsCateFormParams.cat_level = 0
      } else if (this.selectValCate.length === 1) {
        this.addGoodsCateFormParams.cat_pid = this.selectValCate[0]
        this.addGoodsCateFormParams.cat_level = 1
      } else {
        this.addGoodsCateFormParams.cat_pid = this.selectValCate[1]
        this.addGoodsCateFormParams.cat_level = 2
      }
      console.log(this.selectValCate)
      console.log(this.addGoodsCateFormParams)
    },
    // 关闭添加分类对话框
    cloAddGoodsCate() {
      this.$refs.addGoodsCateFormRef.resetFields()
      this.selectValCate = []
    },
    // 提交添加分类
    subAddGoodsCate() {
      this.$refs.addGoodsCateFormRef.validate(async valid => {
        if (!valid) return false
        const { data } = await this.$http.post(
          'categories',
          this.addGoodsCateFormParams
        )
        console.log(data)
        if (data.meta.status !== 201) {
          this.addGoodsCatedialog = false
          return this.$message({ message: '添加分类失败', type: 'error' })
        }
        this.$message({ message: '添加分类成功', type: 'success' })
        this.addGoodsCatedialog = false
        this.getGoodsCateList()
      })
    },
    // 是否显示修改分类按钮
    async modGoodsCateBtn(row) {
      console.log(row)
      const { data } = await this.$http.get(`categories/${row.cat_id}`)
      console.log(data)
      if (data.meta.status !== 200) {
        return this.$message.error(`获取该 ${row.cat_name} 分类失败`)
      }
      // this.$message.error(`获取该 ${row.cat_name} 分类成功`)
      console.log(`获取该 ${row.cat_name} 分类成功`)
      this.modGoodsCateFormParams.cat_name = data.data.cat_name
      this.modGoodsCateFormParams.cat_id = data.data.cat_id
      console.log(this.modGoodsCateFormParams)
      this.modGoodsCatedialog = true
    },
    // 提交修改分类
    subModGoodsCate() {
      this.$refs.modGoodsCateFormRef.validate(async valid => {
        if (!valid) return false
        const {
          data
        } = await this.$http.put(
          `categories/${this.modGoodsCateFormParams.cat_id}`,
          { cat_name: this.modGoodsCateFormParams.cat_name }
        )
        console.log(data)
        if (data.meta.status !== 200) {
          this.addGoodsCatedialog = false
          return this.$message({ message: '修改分类失败', type: 'error' })
        }
        this.$message({ message: '修改分类成功', type: 'success' })
        this.modGoodsCatedialog = false
        this.getGoodsCateList()
      })
    },
    // 删除分类
    delGoodsCateBtn(row) {
      console.log(row)
      this.$confirm(`是否删除 ${row.cat_name} 分类?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data } = await this.$http.delete(`categories/${row.cat_id}`)
          console.log(data)
          if (data.meta.status !== 200) {
            return this.$message({
              type: 'error',
              message: ` ${row.cat_name} 分类删除失败!`
            })
          }
          this.$message({
            type: 'success',
            message: ` ${row.cat_name} 分类删除成功!`
          })
          this.getGoodsCateList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>

<style lang="less" scoped>
.el-cascader {
  width: 100%;
}
.zk-table {
  margin-top: 10px;
}
</style>
